import Vue from 'vue'
import 'normalize.css/normalize.css' // A modern alternative to CSS resets
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
// import locale from 'element-ui/lib/locale/lang/en' // lang i18n
import '@/styles/index.scss' // global css
// import Videoplayer from 'vue-video-player'
// import 'video.js/dist/video-js.css'
// import 'vue-video-player/src/custom-theme.css'


import App from './App'
import store from './store'
import router from './router'
import axios from 'axios'
import '@/icons' // icon

import CryptoJS from 'crypto-js'
import * as echarts from 'echarts' // npm install echarts --save
export const encrypted = (plainText) => {
  try {
    // 获取密钥
    const key = md5Encrypt('茶疗');

    // 将明文转换为字节对象
    const wordArray = CryptoJS.enc.Utf8.parse(plainText);

    // 执行 AES 加密
    const encrypted = CryptoJS.AES.encrypt(wordArray, CryptoJS.enc.Utf8.parse(key), {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7
    });

    // 返回加密后的字符串（Base64 编码）
    return encrypted.toString();
  } catch (e) {
    // 异常处理
    console.error(e);
    return JSON.stringify(plainText); // 或者返回其他错误信息
  }

}
function md5Encrypt (text){
	let  h =  CryptoJS.MD5(text).toString(CryptoJS.enc.Hex).slice(0, 16).toUpperCase();
	return  CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(h)).substring(0, 16);
	};
function decrypt (encryptWord){
  var keyStr =CryptoJS.enc.Utf8.parse(md5Encrypt('茶疗')); //Latin1 w8m31+Yy/Nw6thPsMpO5fg==
  var decrypt = CryptoJS.AES.decrypt(encryptWord, keyStr, {
  mode: CryptoJS.mode.ECB,
  padding: CryptoJS.pad.Pkcs7,
  });
  return CryptoJS.enc.Utf8.stringify(decrypt).toString();
}
Vue.prototype.$echarts = echarts
// import '@/permission' // permission control
Vue.use(ElementUI)

Vue.use(router)
Vue.prototype.$http = axios
Vue.prototype.$store = store
Vue.prototype.$template = store.state.settings.template // 项目名称
Vue.prototype.mainurl = store.state.settings.mainurl

Vue.prototype.$tableHight = (window.innerHeight - 240) + 'px'

var path = Vue.prototype.mainurl
Vue.prototype.$clearTimer = function (time) {
  return time.replace('T', ' ').split('.')[0]
}
Vue.prototype.$address = function(address) {
  var this_ = this
  var promise = new Promise(function(resolve, reject) {
    this_
      .$http({
        url: 'https://restapi.amap.com/v3/geocode/geo',
        method: 'get',
        data: {
          address: address,
          key: '3e2ed72107f91ba0e8a4f25e297eba78'
        },
        params: {
          address: address,
          key: '3e2ed72107f91ba0e8a4f25e297eba78'
        },
        headers: {
          'Content-Type': 'application/json'
        }
      })
      .then(
        (result) => {
          if(store.state.settings.encryption){
            result.data.data=JSON.parse(decrypt(result.data.data))
            resolve(result.data);
          }else{
            resolve(result.data);
          }
        },
        (result) => {
          console.log(result, '后')
          if (result.response.status === 403) {
            localStorage.removeItem('admin_token_sys')
            this_.$router.push('/login')
          }
          reject(result)
        }
      )
  })
  return promise
}
Vue.prototype.request = function (url, method, data) {
  var token = localStorage.getItem('admin_token_sys')
  var this_ = this
  var url_ = path + url
  var promise = new Promise(function (resolve, reject) {
    this_
      .$http({
        url: url_,
        method: method,
        data:  encrypted(JSON.stringify(data)),
        params: method === 'get' || method === 'GET' ? data : null,
        headers: {
          'Content-Type': 'application/json',
          token: token,
        }
      })
      .then(
        (result) => {
          if(result.data.errno == 1) {
            ElementUI.Message.error(result.data.errmsg)

          }
          if(store.state.settings.encryption){
            try {
              const decryptedData = decrypt(result.data.data);
              // 检查解密后的内容是否为字符串且不为空
              if (typeof decryptedData === 'string' && decryptedData.trim() !== '') {
                result.data.data = JSON.parse(decryptedData);
              } else {
                result.data.data = decryptedData;
              }
            } catch (e) {
              // 当解析失败时，保留原始解密数据而不是抛出异常
              // result.data.data = decryptedData;
            }
            resolve(result.data)
          }else{
            resolve(result.data);
          }
        },
        (result) => {
          if (result.response.status === 403) {
            console.log(result, '403')
            localStorage.removeItem('admin_token_sys')
            this_.$router.push('/login')
          }
          reject(result)
        }
      )
  })
  return promise
}
Vue.prototype.$decrypt = function(encryptWord) {

  var keyStr = CryptoJS.enc.Utf8.parse("1YH4uRzhyB5eWBHt"); //Latin1 w8m31+Yy/Nw6thPsMpO5fg==
  var decrypt = CryptoJS.AES.decrypt(encryptWord, keyStr, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7,
  });
  return CryptoJS.enc.Utf8.stringify(decrypt).toString();
}
Vue.prototype.getToken = function () {
  var this_ = this
  var url_ = path + 'admin/uploadToken/'
  var token = localStorage.getItem('admin_token_sys')
  var promise = new Promise(function (resolve, reject) {
    this_
      .$http({
        url: url_,
        method: 'get',
        data: {},
        params: {},
        headers: {
          'Content-Type': 'application/json',
          token: token,

        }
      })
      .then(
        (result) => {
          if(store.state.settings.encryption){
            result.data.data=JSON.parse(decrypt(result.data.data))
            resolve(result.data);
          }else{
            resolve(result.data);
          }
        },
        (result) => {
          if (result.response.status === 403) {
            localStorage.removeItem('admin_token_sys')
          }
          reject(result)
        }
      )
  })
  return promise
}

router.beforeEach((to, from, next) => {
  document.title = `${to.meta.title ? to.meta.title : '后台管理系统'}`
  // const role = localStorage.getItem('admin_token')
  // console.log(to, from, next)
  if (to.matched.length === 0) {
    next('/404')
  } else {
    next()
  }
})
// set ElementUI lang to EN
// Vue.use(ElementUI, { locale })
// 如果想要中文版 element-ui，按如下方式声明

Vue.config.productionTip = false

new Vue({
  el: '#app',
  router,
  store,
  render: h => h(App)
})
